<template>
  <div class="project-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">项目监管平台</h1>
      <div class="header-actions">
        <div class="search-bar">
          <input type="text" v-model="searchKey" @input="handleSearch" placeholder="搜索项目名称或投资主体" />
          <button class="search-button">
            <i class="search-icon">🔍</i>
          </button>
        </div>
      </div>
    </div>

    <!-- 轮播图 -->
    <div class="banner-container">
      <div class="banner-wrapper">
        <div class="banner-slide" v-for="(slide, index) in bannerSlides" :key="index" :class="{ active: currentSlide === index }">
          <img :src="slide.image" class="banner-image" :alt="slide.alt">
          <div class="banner-content">
            <h2 class="banner-title">{{ slide.title }}</h2>
            <p class="banner-description">{{ slide.description }}</p>
          </div>
        </div>
      </div>
      <div class="banner-controls">
        <div class="banner-dots">
          <span 
            v-for="(slide, index) in bannerSlides" 
            :key="index" 
            class="banner-dot" 
            :class="{ active: currentSlide === index }"
            @click="setCurrentSlide(index)">
          </span>
        </div>
      </div>
    </div>

    <!-- 项目列表 -->
    <div class="project-section">
      <div class="section-header">
        <h2 class="section-title">项目列表</h2>
        <div class="section-actions">
          <select v-model="sortOption" class="sort-select" @change="sortProjects">
            <option value="name">按名称排序</option>
            <option value="progress">按进度排序</option>
            <option value="updated">按更新时间排序</option>
          </select>
        </div>
      </div>

      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
      <div v-else-if="projectList.length === 0" class="empty">
        <div class="empty-icon">📂</div>
        <p>暂无项目数据</p>
      </div>
      <div v-else class="project-table">
        <table>
          <thead>
            <tr>
              <th>项目名称</th>
              <th>投资主体</th>
              <th>项目进度</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in projectList" :key="item.id" @click="handleProjectClick(item)" class="project-row">
              <td>
                <div class="project-name-cell">
                  <span class="project-name">{{ item.name }}</span>
                  <span v-if="isRecentlyUpdated(item.updatedAt)" class="update-badge">新</span>
                </div>
              </td>
              <td>{{ item.investor }}</td>
              <td>
                <div class="progress-bar-container">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: item.progress + '%' }"></div>
                  </div>
                  <span class="progress-text">{{ item.progress }}%</span>
                </div>
              </td>
              <td>{{ formatDate(item.updatedAt) }}</td>
              <td>
                <button class="view-button" @click.stop="handleProjectClick(item)">查看详情</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <button class="pagination-button" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
      <span class="pagination-info">{{ currentPage }} / {{ totalPages }}</span>
      <button class="pagination-button" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import config from '@/config.js'
import axios from 'axios'

export default {
  setup() {
    const router = useRouter()
    const searchKey = ref('')
    const projectList = ref([
      {
        id: 1,
        name: '智慧城市建设项目',
        investor: '城市发展投资有限公司',
        image: 'smart-city.png',
        updatedAt: new Date(),
        investorUpdatedAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
        progress: 100
      },
      {
        id: 2,
        name: '绿色能源产业园',
        investor: '新能源科技集团',
        image: 'green-energy.png',
        updatedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
        investorUpdatedAt: new Date(),
        progress: 45
      },
      {
        id: 3,
        name: '智能制造产业基地',
        investor: '工业发展有限公司',
        image: 'smart-manufacturing.png',
        updatedAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000),
        investorUpdatedAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        progress: 30
      },
      {
        id: 4,
        name: '文化创意产业园',
        investor: '文化传媒投资集团',
        image: 'cultural-creative.png',
        updatedAt: new Date(),
        investorUpdatedAt: new Date(),
        progress: 90
      }
    ])
    const loading = ref(false)
    const sortOption = ref('name')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const currentSlide = ref(0)
    
    // 轮播图数据
    const bannerSlides = ref([
      {
        image: '/src/assets/images/projects/swiper1.svg',
        alt: '轮播图1',
        title: '智慧城市建设',
        description: '打造数字化、智能化的现代城市'
      },
      {
        image: '/src/assets/images/projects/swiper2.svg',
        alt: '轮播图2',
        title: '绿色能源产业',
        description: '发展清洁能源，建设美丽家园'
      },
      {
        image: '/src/assets/images/projects/swiper3.svg',
        alt: '轮播图3',
        title: '文化创意产业',
        description: '传承文化精髓，创新发展模式'
      }
    ])
    
    // 设置当前轮播图
    const setCurrentSlide = (index) => {
      currentSlide.value = index
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '暂无数据'
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }
    
    // 项目列表相关计算
    
    // 分页计算
    const totalPages = computed(() => Math.ceil(projectList.value.length / pageSize.value))
    
    // 切换页码
    const changePage = (page) => {
      if (page < 1 || page > totalPages.value) return
      currentPage.value = page
    }
    
    // 排序项目
    const sortProjects = () => {
      const option = sortOption.value
      projectList.value.sort((a, b) => {
        if (option === 'name') {
          return a.name.localeCompare(b.name)
        } else if (option === 'progress') {
          return b.progress - a.progress
        } else if (option === 'updated') {
          return new Date(b.updatedAt) - new Date(a.updatedAt)
        }
        return 0
      })
    }

    // 检查是否最近7天内更新
    const isRecentlyUpdated = (date) => {
      const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
      return new Date(date) > sevenDaysAgo
    }

    // 获取图片URL
    const getImageUrl = (image) => {
      if (!image) return '/src/assets/images/projects/default-project.svg'
      try {
        // Convert .png to .svg extension
        const svgImage = image.replace('.png', '.svg')
        return `/src/assets/images/projects/${svgImage}`
      } catch (e) {
        return '/src/assets/images/projects/default-project.svg'
      }
    }

    // 搜索处理
    const handleSearch = () => {
      loading.value = true
      setTimeout(() => {
        if (searchKey.value) {
          const keyword = searchKey.value.toLowerCase()
          projectList.value = projectList.value.filter(item =>
            item.name.toLowerCase().includes(keyword) ||
            item.investor.toLowerCase().includes(keyword)
          )
        } else {
          // 如果搜索框为空，恢复所有项目
          getProjectList()
        }
        loading.value = false
      }, 300)
    }

    // 查看项目详情
    const handleProjectClick = (project) => {
      console.log('查看项目详情:', project.id)
      router.push(`/project-detail/${project.id}`)
    }

    // 获取项目列表
    const getProjectList = () => {
      loading.value = true
      
      // 尝试从API获取数据
      axios.get(config.getUrl('project_list'), {
        params: {
          pageNo: 1,
          pageSize: 10
        }
      })
      .then(response => {
        console.log('项目列表', response.data)
        if (response.data && response.data.result && response.data.result.records) {
          projectList.value = response.data.result.records.map(item => ({
            id: item.id,
            name: item.xmmc,
            investor: item.tzzt,
            image: null, // API中可能没有图片
            updatedAt: new Date(),
            progress: Math.floor(Math.random() * 100) // 模拟进度
          }))
        }
        loading.value = false
      })
      .catch(error => {
        console.error('获取项目列表失败:', error)
        // 保留默认数据
        loading.value = false
      })
    }

    // 自动轮播
    const startAutoSlide = () => {
      setInterval(() => {
        currentSlide.value = (currentSlide.value + 1) % bannerSlides.value.length
      }, 5000)
    }

    onMounted(() => {
      // 获取项目列表
      getProjectList()
      
      // 初始排序
      sortProjects()
      
      // 启动自动轮播
      startAutoSlide()
    })

    return {
      searchKey,
      projectList,
      loading,
      sortOption,
      currentPage,
      totalPages,
      bannerSlides,
      currentSlide,

      isRecentlyUpdated,
      getImageUrl,
      handleSearch,
      handleProjectClick,
      setCurrentSlide,
      changePage,
      sortProjects,
      formatDate
    }
  }
}
</script>

<style scoped lang="scss">
// 全局变量
$primary-color: #1890FF;
$success-color: #52C41A;
$warning-color: #FAAD14;
$danger-color: #F5222D;
$background-color: #F5F7FA;
$card-color: #FFFFFF;
$text-primary: #333333;
$text-secondary: #666666;
$text-tertiary: #999999;
$border-radius: 8px;
$shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
$transition: all 0.3s ease;

.project-container {
  min-height: 100vh;
  background: $background-color;
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;

  // 页面标题
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    flex-wrap: wrap;
    
    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: $text-primary;
      margin: 0;
      flex: 1;
      min-width: 200px;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      
      .search-bar {
        position: relative;
        width: 300px;
        
        input {
          width: 100%;
          height: 40px;
          border-radius: 20px;
          border: 1px solid #E8E8E8;
          padding: 0 40px 0 15px;
          font-size: 14px;
          outline: none;
          transition: $transition;
          
          &:focus {
            border-color: $primary-color;
            box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
          }
          
          &::placeholder {
            color: $text-tertiary;
          }
        }
        
        .search-button {
          position: absolute;
          right: 5px;
          top: 5px;
          width: 30px;
          height: 30px;
          border: none;
          background: none;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .search-icon {
            font-size: 16px;
            color: $text-tertiary;
          }
        }
      }
    }
  }

  // 轮播图
  .banner-container {
    position: relative;
    height: 300px;
    margin-bottom: 30px;
    border-radius: $border-radius;
    overflow: hidden;
    box-shadow: $shadow;
    
    .banner-wrapper {
      position: relative;
      height: 100%;
      
      .banner-slide {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        transition: opacity 0.5s ease;
        
        &.active {
          opacity: 1;
        }
        
        .banner-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .banner-content {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          padding: 30px;
          background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
          color: white;
          
          .banner-title {
            font-size: 24px;
            font-weight: 600;
            margin: 0 0 10px 0;
          }
          
          .banner-description {
            font-size: 16px;
            margin: 0;
            opacity: 0.8;
          }
        }
      }
    }
    
    .banner-controls {
      position: absolute;
      bottom: 15px;
      right: 30px;
      z-index: 10;
      
      .banner-dots {
        display: flex;
        gap: 8px;
        
        .banner-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.5);
          cursor: pointer;
          transition: $transition;
          
          &.active {
            background-color: white;
            transform: scale(1.2);
          }
        }
      }
    }
  }
  

  
  // 项目列表
  .project-section {
    background: $card-color;
    border-radius: $border-radius;
    padding: 20px;
    box-shadow: $shadow;
    margin-bottom: 30px;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #E8E8E8;
      
      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: $text-primary;
        margin: 0;
      }
      
      .section-actions {
        .sort-select {
          height: 36px;
          border-radius: 4px;
          border: 1px solid #E8E8E8;
          padding: 0 10px;
          font-size: 14px;
          color: $text-secondary;
          outline: none;
          cursor: pointer;
          transition: $transition;
          
          &:focus {
            border-color: $primary-color;
          }
        }
      }
    }
    
    .project-table {
      width: 100%;
      overflow-x: auto;
      
      table {
        width: 100%;
        border-collapse: collapse;
        
        th, td {
          padding: 15px;
          text-align: left;
          border-bottom: 1px solid #E8E8E8;
        }
        
        th {
          font-weight: 600;
          color: $text-primary;
          background-color: #FAFAFA;
        }
        
        .project-row {
          transition: $transition;
          cursor: pointer;
          
          &:hover {
            background-color: #F5F5F5;
          }
          
          .project-name-cell {
            display: flex;
            align-items: center;
            
            .project-name {
              font-weight: 500;
              margin-right: 10px;
            }
            
            .update-badge {
              background: $primary-color;
              color: white;
              font-size: 12px;
              padding: 2px 8px;
              border-radius: 10px;
            }
          }
          
          .progress-bar-container {
            display: flex;
            align-items: center;
            
            .progress-bar {
              flex: 1;
              height: 8px;
              background: #E9ECEF;
              border-radius: 4px;
              overflow: hidden;
              margin-right: 10px;
              
              .progress-fill {
                height: 100%;
                background: linear-gradient(to right, $primary-color, lighten($primary-color, 20%));
                border-radius: 4px;
              }
            }
            
            .progress-text {
              font-size: 14px;
              color: $primary-color;
              font-weight: 500;
              min-width: 40px;
              text-align: right;
            }
          }
          
          .view-button {
            background: $primary-color;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: $transition;
            
            &:hover {
              background: darken($primary-color, 10%);
            }
          }
        }
      }
    }
  }
  
  // 分页
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    
    .pagination-button {
      background: $card-color;
      border: 1px solid #E8E8E8;
      border-radius: 4px;
      padding: 8px 16px;
      font-size: 14px;
      color: $text-secondary;
      cursor: pointer;
      transition: $transition;
      
      &:hover:not(:disabled) {
        border-color: $primary-color;
        color: $primary-color;
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .pagination-info {
      margin: 0 15px;
      font-size: 14px;
      color: $text-secondary;
    }
  }

  .loading,
  .empty {
    text-align: center;
    padding: 40px 0;
    color: $text-tertiary;
    font-size: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid #E8E8E8;
      border-top-color: $primary-color;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 15px;
    }
    
    .empty-icon {
      font-size: 40px;
      margin-bottom: 15px;
      color: $text-tertiary;
    }
    
    p {
      margin: 0;
    }
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .project-container {
    padding: 15px;
    
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      
      .page-title {
        margin-bottom: 15px;
      }
      
      .header-actions {
        width: 100%;
        
        .search-bar {
          width: 100%;
        }
      }
    }
    
    .banner-container {
      height: 200px;
      
      .banner-content {
        .banner-title {
          font-size: 20px;
        }
        
        .banner-description {
          font-size: 14px;
        }
      }
    }
    

    
    .project-table {
      overflow-x: auto;
      
      table {
        min-width: 800px;
      }
    }
  }
}
</style>
